package han.Chensing.CCirnosLibrary.command;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;

public class CommandHandler {
    private final Object attachObject;
    private final HashMap<String, Method> methodHashMap;

    public CommandHandler(Object attachObject){
        this.attachObject=attachObject;
        this.methodHashMap=new HashMap<>();
        Class<?> aClass = attachObject.getClass();
        Method[] methods = aClass.getMethods();
        Object[] parameters = {String[].class};
        for (Method method : methods) {
            if (method.getDeclaredAnnotation(CCirnoCommand.class)==null)
                continue;
            if (!Objects.equals(method.getReturnType(),int.class))
                continue;
            if (!Arrays.deepEquals(method.getParameterTypes(), parameters))
                continue;
            methodHashMap.put(method.getName(),method);
        }
    }

    public int invoke(String line){
        String[] s = line.split("[ ](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
        for (int i=0;i<s.length;i++) {
            String s1=s[i];
            if (s1.startsWith("\""))
                s1=s[i]=s1.substring(1);
            if (s1.endsWith("\""))
                s[i]=s1.substring(0,s1.length()-1);
        }
        Method method = methodHashMap.get(s[0]);
        if (method==null)
            return -1;
        try {
            return (int)method.invoke(attachObject,new Object[]{s});
        } catch (Exception e){
            e.printStackTrace();
            return -2;
        }
    }
}
